package com.wwt.server.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wwt.server.vo.ErrorCode;
import com.wwt.server.vo.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对权限不足等禁止访问做统一处理
 */
@Component
public class MyAccessDenyHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        Result result = Result.fail(ErrorCode.NO_AUTHORITY.getMessage(), ErrorCode.NO_AUTHORITY.getCode());
        response.getWriter().print(new ObjectMapper().writeValueAsString(result));
    }
}
